package db

import (
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	//第三方库
	//"github.com/jinzhu/gorm"                  //gorm库
	//_ "github.com/jinzhu/gorm/dialects/mysql" //gorm对应的mysql驱动
	"gorm.io/gorm/logger"
	"k8s-platform/config"
	"k8s-platform/model"
)

var (
	isInit bool
	//GORM   *gorm.DB
	DB  *gorm.DB
	err error
)

// 初始化db函数，与数据库建立连接
func Init() {

	//判断是否已经初始化了
	if isInit {
		return
	}

	jenkinsConfigTest := &config.JenkinsConfigTest{}
	mysqlconfig, err := jenkinsConfigTest.ConfigTest()
	if err != nil {
		log.Fatalf("Failed to parse configuration: %v", err)
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		mysqlconfig.DbUser,
		mysqlconfig.DbPassword,
		mysqlconfig.DbHost,
		mysqlconfig.DbPort,
		mysqlconfig.DbName)

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second,  // Slow SQL threshold
			LogLevel:                  logger.Error, // Log level
			IgnoreRecordNotFoundError: true,         // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,         // Don't include params in the SQL log
			Colorful:                  false,        // Disable color
		},
	)

	GORM, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic("数据库连接失败" + err.Error())
	}

	// Get the underlying *sql.DB instance
	DBconfig, err := GORM.DB()
	if err != nil {
	}
	//连接池最大允许的空闲连接数，如果没有sql任务需要执行的连接数大于20，超过的连接会被连接池关闭
	DBconfig.SetMaxIdleConns(config.MaxIdleConns)
	//设置了连接可复用的最大时间
	DBconfig.SetMaxOpenConns(config.MaxOpenConns)
	//设置了连接可复用的最大时间
	DBconfig.SetConnMaxLifetime(time.Duration(config.MaxLifeTime))

	isInit = true
	//自动创建数据库表结构
	DB = GORM
	DB.AutoMigrate(model.Createk8s{}, model.Createk8s{}, model.Git{}, model.HostGroup{}, model.Credential{}, model.HostServer{}, model.Jenkinsjoblist{}, model.Cicd_projects{}, model.AppItem{}, model.K8sDeployConfig{})
	//DB.AutoMigrate(model.Credential2{}, model.HostServer2{})
	if err != nil {
		fmt.Println(err)
	}
}
